package com.ruoyi.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.ruoyi.app.domain.AppRecord;
import com.ruoyi.app.domain.vo.AppDynamicVo;
import com.ruoyi.app.domain.vo.AppRecordVo;
import com.ruoyi.app.mapper.AppDynamicMapper;
import com.ruoyi.app.mapper.AppRecordMapper;
import com.ruoyi.app.service.IAppDynamicService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.enums.NoticType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.app.domain.bo.AppDynamicLikeBo;
import com.ruoyi.app.domain.vo.AppDynamicLikeVo;
import com.ruoyi.app.domain.AppDynamicLike;
import com.ruoyi.app.mapper.AppDynamicLikeMapper;
import com.ruoyi.app.service.IAppDynamicLikeService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * APP动态点赞Service业务层处理
 *
 * @author heike
 * @date 2023-01-16
 */
@RequiredArgsConstructor
@Service
public class AppDynamicLikeServiceImpl implements IAppDynamicLikeService {

    private final AppDynamicLikeMapper baseMapper;
    private final AppRecordMapper appRecordMapper;
    private final AppDynamicMapper appDynamicMapper;

    /**
     * 查询APP动态点赞
     */
    @Override
    public AppDynamicLikeVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询APP动态点赞列表
     */
    @Override
    public TableDataInfo<AppDynamicLikeVo> queryPageList(AppDynamicLikeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppDynamicLike> lqw = buildQueryWrapper(bo);
        Page<AppDynamicLikeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询APP动态点赞列表
     */
    @Override
    public List<AppDynamicLikeVo> queryList(AppDynamicLikeBo bo) {
        LambdaQueryWrapper<AppDynamicLike> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppDynamicLike> buildQueryWrapper(AppDynamicLikeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppDynamicLike> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getLikeId() != null, AppDynamicLike::getLikeId, bo.getLikeId());
        lqw.eq(bo.getUserId() != null, AppDynamicLike::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), AppDynamicLike::getType, bo.getType());
        return lqw;
    }

    /**
     * 新增APP动态点赞
     */
    @Override
    public Boolean insertByBo(AppDynamicLikeBo bo) {
        AppDynamicLike add = BeanUtil.toBean(bo, AppDynamicLike.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改APP动态点赞
     */
    @Override
    public Boolean updateByBo(AppDynamicLikeBo bo) {
        AppDynamicLike update = BeanUtil.toBean(bo, AppDynamicLike.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppDynamicLike entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除APP动态点赞
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public AppDynamicLikeVo queryByDynamicIdAndUserId(Long did, Long uid, String type) {
        LambdaQueryWrapper<AppDynamicLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppDynamicLike::getLikeId, did)
            .eq(AppDynamicLike::getUserId, uid)
            .eq(AppDynamicLike::getType, type);
        return baseMapper.selectVoOne(wrapper);
    }

    @Override
    public Boolean queryByUser(Long did, Long uid, String type) {
        LambdaQueryWrapper<AppDynamicLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppDynamicLike::getLikeId, did)
            .eq(AppDynamicLike::getUserId, uid)
            .eq(AppDynamicLike::getType, type);
        return baseMapper.selectCount(wrapper) > 0;
    }

    @Override
    public List<AppDynamicLikeVo> queryByLike(Long id, String type) {
        LambdaQueryWrapper<AppDynamicLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppDynamicLike::getLikeId, id).eq(AppDynamicLike::getType, type);
        return baseMapper.selectVoList(wrapper);
    }


    @Override
    public Long queryCount(Long id, String type) {
        LambdaQueryWrapper<AppDynamicLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppDynamicLike::getLikeId, id).eq(AppDynamicLike::getType, type);
        return baseMapper.selectCount(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HashMap<String, String> like(Long id, Long userId, String type) {
        AppDynamicLikeVo dynamicLikeVo = queryByDynamicIdAndUserId(id, userId, type);
        HashMap<String, String> hashMap = new HashMap<>();
        if (Objects.isNull(dynamicLikeVo)) {
            AppDynamicLikeBo dynamicLikeBo = new AppDynamicLikeBo();
            dynamicLikeBo.setLikeId(id);
            dynamicLikeBo.setUserId(userId);
            dynamicLikeBo.setType(type);
            insertByBo(dynamicLikeBo);
            hashMap.put("msg", "点赞成功");
            hashMap.put("sign", "OK");
            hashMap.put("status", "0");
            //添加动态点赞通知记录
            if (type.equals(Constants.SUCCESS)) {
                AppDynamicVo dynamic = appDynamicMapper.selectVoById(id);
                AppRecord record = new AppRecord();
                record.setRecordId(id);
                record.setUserId(userId);
                record.setRecordUserId(dynamic.getUserId());
                record.setType(NoticType.LIKE.getCode());
                record.setReadStatus(Constants.SUCCESS);
                appRecordMapper.insert(record);
            }
        } else {
            LambdaQueryWrapper<AppRecord> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AppRecord::getRecordId, id).eq(AppRecord::getUserId, userId).eq(AppRecord::getType, NoticType.LIKE.getCode());
            AppRecordVo appRecordVo = appRecordMapper.selectVoOne(wrapper);
            if (Objects.nonNull(appRecordVo)) {
                appRecordMapper.deleteById(appRecordVo.getId());
            }
            baseMapper.deleteById(dynamicLikeVo.getId());
            hashMap.put("msg", "取消点赞成功");
            hashMap.put("sign", "CANCEL");
            hashMap.put("status", "1");
        }
        return hashMap;
    }
}
